package com.ruoyi.busi.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.busi.domain.BusiCompany;
import com.ruoyi.busi.domain.bo.BusiCompanyBo;
import com.ruoyi.busi.domain.vo.BusiCompanyVo;
import com.ruoyi.busi.mapper.BusiCompanyMapper;
import com.ruoyi.busi.service.IBusiCompanyService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.mybatisplus.core.ServicePlusImpl;
import com.ruoyi.common.core.page.PagePlus;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.hyperledger.fabric.gateway.Contract;
import org.hyperledger.fabric.gateway.Network;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 企业Service业务层处理
 *
 * @author qibu
 * @date 2024-11-10
 */
@Slf4j
@Service
public class BusiCompanyServiceImpl extends ServicePlusImpl<BusiCompanyMapper, BusiCompany, BusiCompanyVo> implements IBusiCompanyService {

    @Resource
    private Contract contract;

    @Resource
    private Network network;

    @Autowired
    private ISysUserService sysUserService;

    @Override
    public BusiCompanyVo queryById(Long id) {
        return getVoById(id);
    }

    @Override
    public TableDataInfo<BusiCompanyVo> queryPageList(BusiCompanyBo bo) {
        PagePlus<BusiCompany, BusiCompanyVo> result = pageVo(PageUtils.buildPagePlus(), buildQueryWrapper(bo));
        return PageUtils.buildDataInfo(result);
    }

    @Override
    public List<BusiCompanyVo> queryList(BusiCompanyBo bo) {
        return listVo(buildQueryWrapper(bo));
    }

    private LambdaQueryWrapper<BusiCompany> buildQueryWrapper(BusiCompanyBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BusiCompany> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getName()), BusiCompany::getName, bo.getName());
        lqw.eq(StringUtils.isNotBlank(bo.getIndustry()), BusiCompany::getIndustry, bo.getIndustry());
        lqw.eq(StringUtils.isNotBlank(bo.getProvince()), BusiCompany::getProvince, bo.getProvince());
        lqw.like(StringUtils.isNotBlank(bo.getChannelName()), BusiCompany::getChannelName, bo.getChannelName());
        return lqw;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(BusiCompanyBo bo) {
        BusiCompany add = BeanUtil.toBean(bo, BusiCompany.class);
        validEntityBeforeSave(add);
        boolean flag = save(add);
        Long companyId = add.getId();

        // 保存成功之后自动分配账号和初始密码
        SysUser sysUser = new SysUser();
        sysUser.setNickName(add.getName());
        sysUser.setUserName(add.getName());
        sysUser.setPassword(SecurityUtils.encryptPassword("123456"));
        sysUser.setSex("2");
        sysUser.setDeptId(201L);
        sysUser.setRoleIds(new Long[]{102L});
        sysUserService.insertUser(sysUser);

//        try {
//            byte[] queryAResultBefore = contract.submitTransaction("CreateAsset",companyId.toString(),companyId.toString(),add.getName(),"2024","11","{\"\":\"\"}","100.2");
//            System.out.println("ReadAsset:"+new String(queryAResultBefore, "utf-8"));
//        } catch (ContractException e) {
//            throw new RuntimeException(e);
//        } catch (UnsupportedEncodingException e) {
//            System.out.println("UnsupportedEncodingException:"+e.getMessage());
//            throw new RuntimeException(e);
//        } catch (InterruptedException e) {
//            System.out.println("InterruptedException:"+e.getMessage());
//            throw new RuntimeException(e);
//        } catch (TimeoutException e) {
//            System.out.println("TimeoutException:"+e.getMessage());
//            throw new RuntimeException(e);
//        }
        if (flag) {
            bo.setId(companyId);
        }
        return flag;
    }

    @Override
    public Boolean updateByBo(BusiCompanyBo bo) {
        BusiCompany update = BeanUtil.toBean(bo, BusiCompany.class);
        validEntityBeforeSave(update);
        return updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(BusiCompany entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return removeByIds(ids);
    }

    /**
     * 导入企业数据
     *
     * @param companyList     企业数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importCompany(List<BusiCompany> companyList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(companyList) || companyList.size() == 0) {
            throw new ServiceException("导入企业数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (BusiCompany company : companyList) {
            try {
                // 验证是否存在这个用户
                BusiCompany u = baseMapper.getOneByName(company.getName());
                if (null == u) {
                    this.save(company);
                    // 保存成功之后自动分配账号和初始密码
                    SysUser sysUser = new SysUser();
                    sysUser.setNickName(company.getName());
                    sysUser.setUserName(company.getName());
                    sysUser.setPassword(SecurityUtils.encryptPassword("123456"));
                    sysUser.setSex("2");
                    sysUser.setDeptId(201L);
                    sysUser.setRoleIds(new Long[]{102L});
                    sysUserService.insertUser(sysUser);

                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + company.getName() + " 导入成功");
                } else if (isUpdateSupport) {
                    this.updateById(company);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + company.getName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + company.getName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + company.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
